<?php

class ProfileController extends AppController {
    
    public $uses = array('User','UsersRecoverpwd');
    
    protected function emailRecoverPassword($user, $pwd) {
        App::uses('CakeEmail', 'Network/Email');
        $sitename = Configure::read('Creativos.sitename');
        $from    = Configure::read('Creativos.email.from');
        $subject = Configure::read('Creativos.email.subjects.recoverpwd');
        
        $email = new CakeEmail();
        $email->viewVars(array(
            'User' => $user['User'],
            'UsersRecoverpwd' => $pwd['UsersRecoverpwd']
        ));
        $email->from($from);
        $email->to(array(
            $user['User']['email'] => $user['User']['firstname']." ".$user['User']['lastname']
        ));
        $email->subject($sitename.' - '.$subject);
        $email->template('recoverpwd');
        $email->emailFormat('html');
        $res = $email->send();
        if (!$res) {
            throw new Exception("Unable to send pasword recovery email!");
        }
    }
    
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('recoverpwd','checkrecovery','pwdtoken','updatepwdrec','updatepwdrecerr');
    }
    
    public function recoverpwd() {
        if ($this->request->data) {
            $dbdate = Configure::read('Creativos.formats.dbdate');
            $tokendur = Configure::read('Creativos.register.token_duration');
            $tokendurspan = '+'.$tokendur['value'].' '.$tokendur['type'];
            
            $email = $this->request->data['UsersRecoverpwd']['email'];
            
            //search user by email
            $user = $this->User->find('first', array(
                'conditions' => array(
                    'User.email' => $email
                )
            ));
            if ($user) {
                $user_id = $user['User']['id'];
                
                $currdate = date_create("now");
                $expidate = date_create("now");
                date_modify($expidate, $tokendurspan);
                $pwd = $this->UsersRecoverpwd->find('first', array('conditions' => array('user_id' => $user_id)));
                if ($pwd) {
                    $this->Session->setFlash("[Correo electrónico ya esta en proceso]");
                } else {
                    //No hay registro de recuperaciòn
                    $this->UsersRecoverpwd->create();
                    $this->UsersRecoverpwd->set(array(
                        'user_id' => $user_id,
                        'created' => date_format($currdate, $dbdate),
                        'expires' => date_format($expidate, $dbdate),
                        'token'   => String::uuid()
                    ));
                    $this->UsersRecoverpwd->save();
                    
                    $pwd = $this->UsersRecoverpwd->find('first', array('conditions' => array('user_id' => $user_id)));
                    $this->emailRecoverPassword($user, $pwd);
                    $this->redirect('checkrecovery');
                }
            } else {
                //Send to page "Your email does not exist"
                $this->Session->setFlash("[Correo electrónico no existe en nuestra base de datos]");
            }
        }
    }
    
    public function pwdtoken($id) {
        $this->Session->delete('UsersRecoverpwd');
        $pwd = $this->UsersRecoverpwd->find('first',array(
            'conditions' => array(
                'UsersRecoverpwd.token' => $id
            )
        ));
        if ($pwd) {
            $this->Session->write('UsersRecoverpwd', $pwd);
            $this->redirect('updatepwdrec');
        } else {
            $this->redirect('updatepwdrecerr');
        }
    }
    
    public function checkrecovery() {
    }

	public function stats() {
	}
    
    public function updatepwdrecerr() {
    }
    
    public function updatepwdrec() {
        $pwds = $this->Session->read('UsersRecoverpwd');
        $pwd = $this->UsersRecoverpwd->find('first',array(
            'conditions' => array(
                'UsersRecoverpwd.token' => $pwds['UsersRecoverpwd']['token']
            )
        ));
        
        if (empty($pwds) || !$pwd) {
            $this->redirect('updatepwdrecerr');
        }
        
        if ($this->request->data) {
            $this->User->set($this->request->data);
            if ($this->User->validates(array('fieldList' => array('password', 'confirm_password')))) {
                $pwd = $this->Session->read('UsersRecoverpwd');
                $user_id = $pwd['UsersRecoverpwd']['user_id'];
                $this->User->updateAll(
                    array(
                        'User.password' =>  "'".$this->Auth->password($this->request->data['User']['password'])."'"
                    ),
                    array('User.id' => $user_id)
                );
                
                $this->UsersRecoverpwd->deleteAll(array(
                    'UsersRecoverpwd.user_id' => $user_id
                ));
                $this->Session->delete('UsersRecoverpwd');
                $user = $this->User->find('first', array('conditions' => array('User.id' => $user_id)));
                $this->Auth->login($user);
                $this->redirect(array('controller' => 'home', 'action' => 'index'));
            }
        }
	}

	public function updatepwd() {
	}

	public function me() {
	}
}

?>
